package common

import (
	"douhu_backend/internal/config"
	"douhu_backend/internal/log"
	"fmt"
	"math/rand"
	"strconv"
	"time"

	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	sms "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sms/v20210111"
)

// SMSService 短信服务接口
type SMSService interface {
	// SendLoginCode 发送登录验证码
	SendLoginCode(phone string) (string, error)
	// SendRegisterCode 发送注册验证码
	SendRegisterCode(phone string) (string, error)
	// SendResetPasswordCode 发送重置密码验证码
	SendResetPasswordCode(phone string) (string, error)
	// GetDailyLimit 获取每日发送限制
	GetDailyLimit() int
	// GetExpireMinutes 获取验证码过期分钟数
	GetExpireMinutes() int
}

// TencentSMSService 腾讯云短信服务实现
type TencentSMSService struct {
	client *sms.Client
	config *config.SMS
}

// NewTencentSMSService 创建腾讯云短信服务实例
func NewTencentSMSService() (*TencentSMSService, error) {
	smsConfig := config.Conf.SMS
	if smsConfig == nil {
		return nil, fmt.Errorf("sms config is nil")
	}

	// 调试模式下，不需要真实的腾讯云配置
	if smsConfig.SecretId == "debug" || smsConfig.SecretId == "your_secret_id" {
		log.Infof("SMS service running in DEBUG mode")
		return &TencentSMSService{
			client: nil, // 调试模式下client为nil
			config: smsConfig,
		}, nil
	}

	credential := common.NewCredential(smsConfig.SecretId, smsConfig.SecretKey)

	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = "sms.tencentcloudapi.com"

	client, err := sms.NewClient(credential, smsConfig.Region, cpf)
	if err != nil {
		return nil, fmt.Errorf("create tencent sms client failed: %v", err)
	}

	return &TencentSMSService{
		client: client,
		config: smsConfig,
	}, nil
}

// SendLoginCode 发送登录验证码
func (s *TencentSMSService) SendLoginCode(phone string) (string, error) {
	if s.config == nil {
		return "", fmt.Errorf("sms config is nil")
	}

	code := s.generateCode()
	templateId := ""
	if s.config.Templates != nil {
		templateId = s.config.Templates["login"]
	}
	if templateId == "" {
		return "", fmt.Errorf("login template id not configured")
	}

	err := s.sendSMS(phone, templateId, []string{code, strconv.Itoa(s.config.ExpireMinutes)})
	if err != nil {
		log.Errorf("send login code to phone %s failed: %v", phone, err)
		return "", err
	}

	log.Infof("✅ send login code to phone %s success, code: %s", phone, code)
	return code, nil
}

// SendRegisterCode 发送注册验证码
func (s *TencentSMSService) SendRegisterCode(phone string) (string, error) {
	if s.config == nil {
		return "", fmt.Errorf("sms config is nil")
	}

	code := s.generateCode()
	templateId := ""
	if s.config.Templates != nil {
		templateId = s.config.Templates["register"]
	}
	if templateId == "" {
		return "", fmt.Errorf("register template id not configured")
	}

	err := s.sendSMS(phone, templateId, []string{code, strconv.Itoa(s.config.ExpireMinutes)})
	if err != nil {
		log.Errorf("send register code to phone %s failed: %v", phone, err)
		return "", err
	}

	log.Infof("✅ send register code to phone %s success, code: %s", phone, code)
	return code, nil
}

// SendResetPasswordCode 发送重置密码验证码
func (s *TencentSMSService) SendResetPasswordCode(phone string) (string, error) {
	if s.config == nil {
		return "", fmt.Errorf("sms config is nil")
	}

	code := s.generateCode()
	templateId := ""
	if s.config.Templates != nil {
		templateId = s.config.Templates["resetPassword"]
	}
	if templateId == "" {
		return "", fmt.Errorf("reset password template id not configured")
	}

	err := s.sendSMS(phone, templateId, []string{code, strconv.Itoa(s.config.ExpireMinutes)})
	if err != nil {
		log.Errorf("send reset password code to phone %s failed: %v", phone, err)
		return "", err
	}

	log.Infof("✅ send reset password code to phone %s success, code: %s", phone, code)
	return code, nil
}

// sendSMS 发送短信的底层方法
func (s *TencentSMSService) sendSMS(phone, templateId string, params []string) error {
	// 调试模式下，直接在日志中打印验证码
	if s.client == nil {
		if len(params) > 0 {
			log.Infof("=====================================")
			log.Infof("📱 DEBUG MODE - SMS VERIFICATION CODE")
			log.Infof("=====================================")
			log.Infof("📞 Phone Number: %s", phone)
			log.Infof("🔐 Verification Code: %s", params[0])
			log.Infof("⏰ Expire Minutes: %s", params[1])
			log.Infof("📋 Template ID: %s", templateId)
			log.Infof("=====================================")
		}
		return nil
	}

	request := sms.NewSendSmsRequest()
	request.PhoneNumberSet = common.StringPtrs([]string{"+86" + phone})
	request.SmsSdkAppId = common.StringPtr(s.config.AppId)
	request.SignName = common.StringPtr(s.config.SignName)
	request.TemplateId = common.StringPtr(templateId)
	request.TemplateParamSet = common.StringPtrs(params)

	response, err := s.client.SendSms(request)
	if err != nil {
		if _, ok := err.(*errors.TencentCloudSDKError); ok {
			return fmt.Errorf("tencent cloud sdk error: %v", err)
		}
		return fmt.Errorf("send sms request failed: %v", err)
	}

	// 检查发送结果
	if len(response.Response.SendStatusSet) > 0 {
		status := response.Response.SendStatusSet[0]
		if *status.Code != "Ok" {
			return fmt.Errorf("send sms failed, code: %s, message: %s",
				*status.Code, *status.Message)
		}
	}

	return nil
}

// generateCode 生成6位数字验证码
func (s *TencentSMSService) generateCode() string {
	rand.Seed(time.Now().UnixNano())
	code := rand.Intn(900000) + 100000 // 生成100000-999999之间的数字
	return strconv.Itoa(code)
}

// GetExpireMinutes 获取验证码过期时间（分钟）
func (s *TencentSMSService) GetExpireMinutes() int {
	if s.config == nil {
		return 5 // 默认5分钟
	}
	return s.config.ExpireMinutes
}

// GetDailyLimit 获取每日发送限制
func (s *TencentSMSService) GetDailyLimit() int {
	if s.config == nil {
		return 10 // 默认每日10条
	}
	return s.config.DailyLimit
}
